/*
 * @Author: yanjikun
 * @Date: 2021-06-29 17:40:11
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-30 14:17:59
 * @Description: file content
 */

import { watch, ref, computed, unref } from 'vue'
import { RouteLocationNormalized, RouteLocationRaw, useRoute } from 'vue-router'
import { storage } from '@/utils/Storage'
import router from '@/router'
import { message } from 'ant-design-vue'
import { IRouteItem, useTabsViewStore } from '@/store/modules/tabsView'
import { Key } from 'ant-design-vue/es/_util/type'
import { TABS_LIST } from '@/enums/cacheEnums'
import { LOGIN_PATH } from '@/router/constant'

export const useTabsView = () => {
  const route = useRoute()
  const TabsViewStore = useTabsViewStore()
  /**设置初始选中key */
  const activeKey = ref(route.fullPath)
  let routes: IRouteItem[] = []
  /**格式化路由信息 */
  const getSimpleRoute = (route: RouteLocationNormalized): IRouteItem => {
    const { fullPath, path, name, meta, hash, query, params } = route
    return { fullPath, path, name: name as string, meta, hash, query, params }
  }
  /**设置初始路由 */
  try {
    const routesStr = storage.get(TABS_LIST)
    routes = routesStr ?? [getSimpleRoute(route)]
  } catch (error) {
    routes = [getSimpleRoute(route)]
  }
  TabsViewStore.initTabsList(routes)
  /**获取路由列表 */
  const tabsList = computed(() => TabsViewStore.tabsList)
  /**移除路由 */
  const removeTabs = (route: IRouteItem) => {
    if (unref(tabsList).length === 1) {
      message.warning('这已经是最后一页，不能再关闭了！')
      return
    }
    if (route.fullPath === activeKey.value) {
      const index = unref(tabsList).findIndex((item) => item.fullPath === route.fullPath)
      const checkIndex = index >= 1 ? index - 1 : index + 1
      activeKey.value = unref(tabsList)[checkIndex].fullPath
      handleChangeRoute(activeKey.value)
    }
    TabsViewStore.removeTabsList(route)
  }
  /**切换路由 */
  const handleChangeRoute = (key: Key) => {
    router.push(key as RouteLocationRaw)
  }
  /**删除路由 */
  const handleEditRoute = (key: Key | KeyboardEvent | MouseEvent, action: 'add' | 'remove') => {
    if (action === 'remove') {
      removeTabs(unref(tabsList).find((item) => item.fullPath === key)!)
    }
  }
  /**关闭左侧标签页 */
  const handleCloseLeftTabs = (route: IRouteItem) => {
    TabsViewStore.closeLeftTabs(route)
    activeKey.value = route.fullPath
    router.replace(route.fullPath)
  }
  /**关闭右侧标签页 */
  const handleCloseRightTabs = (route: IRouteItem) => {
    TabsViewStore.closeRightTabs(route)
    activeKey.value = route.fullPath
    router.replace(route.fullPath)
  }
  const handleCloseOtherTabs = (route: IRouteItem) => {
    TabsViewStore.closeOtherTabs(route)
    activeKey.value = route.fullPath
    router.replace(route.fullPath)
  }
  /**缓存路由信息 */
  window.addEventListener('beforeunload', () => {
    storage.set(TABS_LIST, unref(tabsList))
  })
  watch(
    () => route.fullPath,
    () => {
      const noFoundRoutes: string[] = [LOGIN_PATH]
      unref(tabsList).forEach((item) => {
        if (!router.hasRoute(item.name)) {
          noFoundRoutes.push(item.name)
        }
      })
      if (noFoundRoutes.length !== 0) {
        TabsViewStore.initTabsList(
          unref(tabsList).filter((item) => !noFoundRoutes.includes(item.name)),
        )
      }
    },
  )
  watch(
    () => route.fullPath,
    () => {
      if (route.meta.hidden) {
        return
      }
      activeKey.value = route.fullPath
      TabsViewStore.addTabsList(getSimpleRoute(route))
    },
  )
  return {
    route: computed(() => getSimpleRoute(route)),
    tabsList,
    activeKey,
    handleChangeRoute,
    handleEditRoute,
    removeTabs,
    handleCloseLeftTabs,
    handleCloseRightTabs,
    handleCloseOtherTabs,
  }
}
